// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV
}) // 使用当前云环境

const db = cloud.database()

const OrderStatus = {
  PENDING_PAYMENT: 5, // 待支付
  PENDING_DELIVERY: 10, // 待发货
  DELIVERY: 15, // 配送中
  COMPLETE: 50, // 已完成/待评价
  PENDING_REFOUND: 60, // 待退款

  PENDING_RECEIPT: 40, // 待收货
  PAYMENT_TIMEOUT: 80, // 已取消，支付超时
  CANCELED_NOT_PAYMENT: 80, // 已取消，未支付主动取消
  CANCELED_PAYMENT: 80, // 已取消，已支付主动取消
  CANCELED_REJECTION: 80, // 已取消，拒收
  descRefoundStatus(refoundInfo) {
    const desc = {
      'wait': '申请退款',
      'success': '已退款',
      'cancel': '已取消退款'
    }
    if (!refoundInfo?.status) return ''
    return (refoundInfo.statusDesc = desc[refoundInfo.status])
  },
  getName(status) {
    switch (status) {
      case OrderStatus.PENDING_PAYMENT:
        return '待付款'
      case OrderStatus.PENDING_DELIVERY:
        return '待配送'
      case OrderStatus.DELIVERY:
        return '配送中'
      case OrderStatus.COMPLETE:
        return '已送达'
      default:
        return ''
    }
  }
};

// 云函数入口函数
exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext()

  const {
    user,
    pageNum,
    pageSize,
    orderStatus,
    search
  } = event

  const _ = db.command
  user.nshops = user.shops.map(s => s * 1)
  // 优化后的聚合查询
  const resOrders = await db.collection('orders').aggregate()
    .sort({
      createTime: -1
    })
    .lookup({
      from: 'delivery_addr',
      localField: '_openid',
      foreignField: '_openid',
      as: 'deliveryInfo'
    })
    .unwind({
      path: '$deliveryInfo',
      preserveNullAndEmptyArrays: false
    })
    .match({
      'deliveryInfo.shop': _.in(user.shops).or(_.in(user.nshops)), // 直接关联店铺条件
      ...(orderStatus > 0 && {
        status: OrderStatus.getName(orderStatus),
        ticketInfo: _.exists(false)
      }),
      ...(!(orderStatus > 0) && {
        ...(search.ticket && {
          ticketInfo: _.exists(true)
        }),
        ...(search.ticketOrderId && {
          ticketOrderId: _.exists(true)
        }),
      }),
      ...(search.orderId && {
        _id: search.orderId
      }),
      ...(search.openId && {
        _openid: search.openId
      })
    })
    .skip((pageNum - 1) * pageSize)
    .limit(pageSize)
    .end()

  return resOrders
}